﻿using System;

namespace Shot.Session.Cookies
{
    /// <summary>
    /// Implementation of cookie manager which communicates over the cookie API
    /// </summary>
    public class CookieManager : ICookieManager
    {
        public AppInstance Instance { get; set; }

        public void Set(string name, object value, Action callback = null)
        {
            var randomCallbackGuidString = Guid.NewGuid().ToString();

            var cookieObject = new Cookie
            {
                Name = name,
                Value = value
            };

            var request = new CookieAccessRequest
            {
                Callback = randomCallbackGuidString,
                Cookie = cookieObject,
                RequestType = CookieAccessRequest.SetCookie
            };

            Instance.On(randomCallbackGuidString, o => { if (callback != null) callback.Invoke(); });
            Instance.Emit("Cookie", request);
        }

        public void Get(string name, Action<object> callback)
        {
            var randomCallbackGuidString = Guid.NewGuid().ToString();

            var cookieObject = new Cookie
            {
                Name = name,
                Value = ""
            };

            var request = new CookieAccessRequest
            {
                Callback = randomCallbackGuidString,
                Cookie = cookieObject,
                RequestType = CookieAccessRequest.GetCookie
            };

            Instance.On(randomCallbackGuidString, returnedCookie =>
            {
                var returnedValue = returnedCookie.value;
                callback.Invoke(returnedValue);
            });

            Instance.Emit("Cookie", request);
        }
    }
}
